package www.lagou.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.apache.commons.dbutils.DbUtils;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DruidUtil {

    private static DataSource dataSource;

    static {
        Properties properties = new Properties();
        InputStream resourceAsStream = DruidUtil.class.getClassLoader().getResourceAsStream("druid.properties");
        try {
            properties.load(resourceAsStream);
            dataSource =  DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取连接的方法
    public static Connection getConnection(){
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            connection.setAutoCommit(false);//从当前线程对象中取出的连接，并开始事务
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    //获取数据库连接池对象的方法
    public static DataSource getDataSource(){
        return dataSource;
    }

    //5.释放资源的方法
    public static void close(Connection conn, Statement stat){
        if (conn!=null && stat!=null){
            try {
                //归还连接
                stat.close();
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
    }

    public static void close(Connection conn, Statement stat, ResultSet res){
        if (conn!=null && stat!=null && res!=null){
            try {
                //归还连接
                res.close();
                stat.close();
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
    }


    public static void commit(){
        try {
            getConnection().commit();//提交事务
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void rollback(){
        try {
            getConnection().rollback();//回滚事务
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
